package com.szp.spCloud.codeService.service.impl;

import com.szp.spCloud.codeService.dao.CodeRepository;
import com.szp.spCloud.codeService.service.CodeService;
import com.szp.spCloud.common.pojo.AuthCode;
import com.szp.spCloud.common.service.MailService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;
@RefreshScope
@Service
public class CodeServiceImpl implements CodeService{
    @Value("${myconfig.code.expireTime}")
    private int expireSeconds;
    @Reference
    MailService mailService;
    @Autowired
    CodeRepository codeRepository;
    @Override
    public boolean saveCode(String email) {
        String code = UUID.randomUUID().toString().replace("-", "").substring(0, 6);


        // 保存到数据库
        AuthCode authCode = new AuthCode();
        authCode.setCode(code);
        authCode.setEmail(email);

        long current = System.currentTimeMillis();
        Date currentDate = new Date(current);
        authCode.setCreateTime(currentDate);

        long expire = current + expireSeconds *60 * 1000;
        Date expireDate = new Date(expire);
        authCode.setExpireTime(expireDate);

        codeRepository.save(authCode);

        // 发送邮件
        return mailService.sendMail(email, code);
    }


}
